<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Model\Logic;

use Swoft\Apollo\Config;
use Swoft\Apollo\Exception\ApolloException;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;

use App\Model\Dao\UserDao;
use App\Model\Data\UserData;

/**
 * Class UserLogic
 *
 * @since 2.0
 *
 * @Bean()
 */
class UserLogic
{
    /**
     * @Inject()
     *
     * @var UserDao
     */
    private $userDao;

    /**
     * @Inject()
     *
     * @var UserData
     */
    private $userData;

    public function login(string $name, string $password){
        $data = [];
        $rs = $this->userDao->findUserInfoByName($name);
        if($rs && isset($rs['password']) && md5($password) == $rs['password']){
            $rsUser = $this->userDao->getUserInfo($rs['id']);
            if($rsUser){
                $data = [
                    'userId' => $rs['id'],
                    'nickname' => $rsUser['nickname'],
                    'avatar' => 'avatar.jpg',
                ];
            }
        }
        return $data;
    }

    public function register(string $nickname, string $name, string $password){
        if(!$nickname || !$name || !$password){
            return false;
        }
        //判断用户名是否已经存在
        $rs = $this->userDao->findUserInfoByName($name);
        if($rs) {
            return false;
        }
        $userId = $this->userDao->saveUser($name, $password);
        if($userId){
            $this->userDao->saveUserInfo($userId, $nickname);
        }
        return true;
    }

    public function getUserInfo(int $userId){
        return $this->userDao->getUserInfo($userId);
    }

    public function updateUserInfo(int $userId, string $nickname, string $introduction, string $homepage){
        if(!$nickname || !$userId){
            return false;
        }
        return $this->userDao->updateUserInfo($userId, $nickname, $introduction, $homepage);
    }

    public function getUserTop(){
        $data = [];
        $rs = $this->userData->getUserCountList();
        if($rs){
            foreach($rs as $key => $val){
                $rsUser = $this->userData->getUserInfo($val);
                if($rsUser){
                    array_push($data, [
                        'userId' => $rsUser['userId'],
                        'fans' => $rsUser['fans'],
                        'orderCount' => $rsUser['orderCount'],
                        'nickname' => $rsUser['nickname'],
                        'avatar' => $rsUser['avatar'],
                    ]);
                }
            }
        }
        return $data;
    }
}
